<?php

namespace app\controllers;

use \app\models\tableModel\base\A5;
use app\service\tool\ConvertService;
use QL\QueryList;

/**
 * A5采集任务
 */
class A5Controller extends BaseController
{

    /**
     * 采集列表页
     */
    public function actionIndex()
    {

        $code = '002362';
        $host = "https://gushitong.baidu.com/opendata?openapi=1&dspName=iphone&tn=tangram&client=app&query={$code}&code=&word={$code}&resource_id=5429&ma_ver=4&finClientType=pc";
        // ********** 0、右侧小额任务 **********
        // 待采集的页面地址
        $content = file_get_contents($host);
        $content = iconv('GBK', 'UTF-8//IGNORE', $content);
        $content = json_decode($content, true);
        $indDesc = $content['Result'][1]['DisplayData']['resultData']['tplData']['result']['minute_data']['pankouinfos']['list'];
        $indDesc = array_column($indDesc, null, 'ename');
        var_dump(
            $indDesc['totalShareCapital']
        );die;



        // 采集规则
        $rules = [
            // 文章标题
            'title' => ['.m-urgent>ul>li>p>a', 'text'],
            // 价格
            'price' => ['.m-urgent>ul>li>p>i', 'text'],
            // 连接
            'link' => ['.m-urgent>ul>li>p>a', 'href']
        ];
        // 切片选择器
        $range = '';
        $data = QueryList::Query($content, $rules, $range)->data;
        krsort($data);
        $model = new A5();
        $copyModel = null;
        $smallSucCount = 0;
        $smallErrCount = 0;
        $record = null;
        foreach ($data as $k => &$v) {
            $v['title'] = ConvertService::clearAllSpace($v['title']);
            // 替换换行符
            $v['title'] = preg_replace('/[\n|\r|\n\r]/', '', $v['title']);
            // 替换开始价格
            $v['title'] = preg_replace('/[0-9]*\.[0-9]{0,2}/', '', $v['title']);

            $v['desc'] = '';
            $v['price'] = ConvertService::clearAllSpace($v['price']);

            // 克隆
            $copyModel = clone $model;
            $record = $copyModel::find()->where([
                'link' => $v['link']
            ])->asArray()->one();
            if (!empty($record)) {
                continue;
            }
            $copyModel->setAttributes([
                'title' => $v['title'],
                'desc' => $v['desc'],
                'price' => $v['price'],
                'link' => $v['link'],
                'add_time' => time(),
                'type' => 1
            ]);
            // 填写失败  失败次数增加
            if (!$copyModel->validate() || !$copyModel->save()) {
                $smallErrCount = $smallErrCount + 1;
                continue;
            }
            // 成功 次数增加
            $smallSucCount = $smallSucCount + 1;
        }
        // ********** 1、小额任务 **********
        // 待采集的页面地址
        $content = file_get_contents($host.'tasklist-u-1.html');
        $content = iconv('GBK', 'UTF-8//IGNORE', $content);

        // 采集规则
        $rules = [
            // 文章标题
            'title' => ['.m-tk-list>ul>li>.col-sm-7>h3>a', 'text'],
            // 价格
            'price' => ['.m-tk-list>ul>li>.col-sm-7>h3>a>i', 'text'],
            // 详情
            'desc' => ['.m-tk-list>ul>li>.col-sm-7>p', 'text'],
            // 连接
            'link' => ['.m-tk-list>ul>li>.col-sm-7>h3>a', 'href']
        ];

        // 切片选择器
        $range = '';
        $data = QueryList::Query($content, $rules, $range)->data;
        krsort($data);
        $model = new A5();
        $copyModel = null;
        $smallSucCount = 0;
        $smallErrCount = 0;
        $record = null;
        foreach ($data as $k => &$v) {
            $v['title'] = ConvertService::clearAllSpace($v['title']);
            // 替换换行符
            $v['title'] = preg_replace('/[\n|\r|\n\r]/', '', $v['title']);
            // 替换开始价格
            $v['title'] = preg_replace('/[0-9]*\.[0-9]{0,2}/', '', $v['title']);

            $v['desc'] = ConvertService::clearAllSpace($v['desc']);
            $v['desc'] = preg_replace('/[\n|\r|\n\r]/', '', $v['desc']);
            $v['price'] = ConvertService::clearAllSpace($v['price']);

            // 克隆
            $copyModel = clone $model;
            $record = $copyModel::find()->where([
                'link' => $v['link']
            ])->asArray()->one();
            if (!empty($record)) {
                continue;
            }
            $copyModel->setAttributes([
                'title' => $v['title'],
                'desc' => $v['desc'],
                'price' => $v['price'],
                'link' => $v['link'],
                'add_time' => time(),
                'type' => 1
            ]);
            // 填写失败  失败次数增加
            if (!$copyModel->validate() || !$copyModel->save()) {
                $smallErrCount = $smallErrCount + 1;
                continue;
            }
            // 成功 次数增加
            $smallSucCount = $smallSucCount + 1;
        }
        // 存储

        // ********** 2、大额任务 **********
        // 待采集的页面地址
        $content = file_get_contents($host.'tasklist.html');
        $content = iconv('GBK', 'UTF-8//IGNORE', $content);
        // 采集规则
//        $rules = [
//            // 文章标题
//            'title' => ['.m-urgent>ul>li>p>a', 'text'],
//            // 价格
//            'price' => ['.m-urgent>ul>li>p>i', 'text'],
//            // 连接
//            'link' => ['.m-urgent>ul>li>p>a', 'href'],
//            'desc' => 233
//        ];

        // 切片选择器
        $range = '';
        $dataJiaJi = QueryList::Query($content, $rules, $range)->data;
        krsort($dataJiaJi);
        $normalSucCount = 0;
        $normalErrCount = 0;
        foreach ($dataJiaJi as $k1 => &$v1) {
            $v1['title'] = ConvertService::clearAllSpace($v1['title']);
            // 替换换行符
            $v1['title'] = preg_replace('/[\n|\r|\n\r]/', '', $v1['title']);
            // 替换开始价格
            $v1['title'] = preg_replace('/[0-9]*\.[0-9]{0,2}/', '', $v1['title']);

            $v1['desc'] = empty($v1['desc']) ? '' : $v1['desc'];
            $v1['desc'] = ConvertService::clearAllSpace($v1['desc']);
            $v1['desc'] = preg_replace('/[\n|\r|\n\r]/', '', $v1['desc']);
            $v1['price'] = ConvertService::clearAllSpace($v1['price']);

            // 克隆
            $copyModel = clone $model;
            $record = $copyModel::find()->where([
                'link' => $v['link']
            ])->asArray()->one();
            if (!empty($record)) {
                continue;
            }
            $copyModel->setAttributes([
                'title' => $v1['title'],
                'desc' => $v1['desc'],
                'price' => $v1['price'],
                'link' => $v1['link'],
                'add_time' => time(),
                'type' => 2
            ]);
            // 填写失败  失败次数增加
            if (!$copyModel->validate() || !$copyModel->save()) {
                $normalErrCount = $normalErrCount + 1;
                continue;
            }
            // 成功 次数增加
            $normalSucCount = $normalSucCount + 1;
        }

        // 取出最后20条数据
        $form = $this->get('searchForm');
        $form = empty($form) ? [] : $form;
        $form = array_filter(array_unique($form));
        // $form['status'] = empty($form['status']) ? 0 : $form['status'];
        $base = $model::find()->where($form)->orderBy('`id` DESC');
        $count = $base->count();
        $page = intval(\Yii::$app->request->get('page'));
        $page = (($page - 1) < 0 ? 0 : ($page - 1));
        $limit = 20;
        $returnList = $base->offset($page * $limit)->limit($limit)->asArray()->all();
        foreach ($returnList as $k2 => &$v2) {
            $v2['add_time_text'] = date('Y-m-d H:i:s', $v2['add_time']);
            $v2['link'] = $host . $v2['link'];
            $v2['type_text'] = '未知';
            if ($v2['type'] == 1) {
                $v2['type_text'] = '小额';
            } else {
                $v2['type_text'] = '大额';
            }
        }

        $this->jsonSuccess('成功', [
            'list' => $returnList,
            'total' => $count,
            'normalSucCount' => $normalSucCount,
            'normalErrCount' => $normalErrCount,
            'smallSucCount' => $smallSucCount,
            'smallErrCount' => $smallErrCount
        ]);
    }

    /**
     * 采集列表页
     */
    public function actionSee()
    {

        $id = \Yii::$app->request->post('id');
        $model = new A5();
        $returnList = $model::updateAll(['status' => 1], [
            'id' => $id
        ]);

        $this->jsonSuccess('成功', []);
    }


    /**
     * 不展示
     */
    public function actionNoSee()
    {

        $id = \Yii::$app->request->post('id');
        $model = new A5();
        $returnList = $model::updateAll(['status' => -1], [
            'id' => $id
        ]);

        $this->jsonSuccess('成功', []);
    }
}
